package com.zzl.springboot_mybatis_demo.rest;

import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * Description：测试RestTempl工具类
 * Created by 朱正磊 on 2019-08-18 22:40
 */
@SuppressWarnings("ALL")
@Component
public class TestRest {

    private String restUrl;

    @Resource
    private RestTemplate restTemplate;

    public TestRest() {
    }

    public String getRestUrl() {
        return this.restUrl;
    }

    public void setRestUrl(String restUrl) {
        this.restUrl = restUrl;
    }

    public String get(String path, Object... params) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json; charset=UTF-8");
        HttpEntity entity = new HttpEntity<>(null, headers);
        String url = this.getRestUrl() + path;
        System.out.println("to data service url:" + url);
        ResponseEntity<String> responseEntity = this.restTemplate.exchange(url, HttpMethod.GET, entity, String.class, params);
        return responseEntity.getBody();
    }

    public String post(String path, String reqJson, Object... params) {
        String url = this.getRestUrl() + path;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", "application/json; charset=UTF-8");
        HttpEntity entity = new HttpEntity<>(reqJson, headers);
        ResponseEntity<String> resp = this.restTemplate.exchange(url, HttpMethod.POST, entity, String.class, params);
        return resp.getBody();
    }

    public String put(String path, String reqJson, Object... params) {
        String url = this.getRestUrl() + path;
        System.out.println("reqest json:" + reqJson);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", "application/json; charset=UTF-8");
        HttpEntity entity = new HttpEntity<>(reqJson, headers);
        ResponseEntity<String> resp = this.restTemplate.exchange(url, HttpMethod.PUT, entity, String.class, params);
        return resp.getBody();
    }

    public String delete(String path, Object... params) {
        String url = this.getRestUrl() + path;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", "application/json; charset=UTF-8");
        HttpEntity entity = new HttpEntity<>(null, headers);
        ResponseEntity<String> resp = this.restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class, params);
        return resp.getBody();
    }

}
